package io.github.xxyopen.novel.app;

import io.github.xxyopen.novel.app.chatmemory.InMysqlChatMemory;
import io.github.xxyopen.novel.core.auth.UserHolder;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

@Component
public class AiHelperApp {


    private static final String SYSTEM_PROMPT = "你是一个小说推荐智能助手，你能够根据用户的需求推荐出用户想看的小说";
    private final String CHAT_MEMORY_CONVERSATION_ID_KEY = "chat_memory_conversation_id";

    private final ChatClient chatClient;

    public AiHelperApp(ChatModel dashScopeChatModel,InMysqlChatMemory inMysqlChatMemory){


        MessageChatMemoryAdvisor messageChatMemoryAdvisor = MessageChatMemoryAdvisor.builder(inMysqlChatMemory).build();
        chatClient = ChatClient.builder(dashScopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(messageChatMemoryAdvisor)
                .build();
    }

    public Flux<String> chat(String chatId, String message){

        Long userId = UserHolder.getUserId();
        chatId = chatId + "." + userId;
        String finalChatId = chatId;
        return chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, finalChatId))
                .stream().content();

    }
}
